<template>
  <v-chart
    :style="style"
    :option="widget.option"
    :update-options="{ notMerge: true }"
    autoresize
  />
</template>
<script>
import _ from "lodash";
import { renderWidgetData } from "../tools/DataUtils";
export default {
  props: {
    widget: {
      type: [Object],
      default: () => {},
    },
  },
  data() {
    return {
      render: null,
    };
  },
  computed: {
    style() {
      return {
        width: this.widget.location.width + "px",
        height: this.widget.location.height + "px",
      };
    },
    option() {
      return {
        customRadius: this.widget.option.radar.customRadius,
        customOpacity: this.widget.option.radar.customOpacity,
      };
    },
    data() {
      return this.widget.data;
    },
    refresh() {
      return this.widget.service.timestamp;
    },
  },
  watch: {
    option: {
      handler(val) {
        this.widget.option.radar.radius[0] = val.customRadius[0] + "%";
        this.widget.option.radar.radius[1] = val.customRadius[1] + "%";
        for (let i = 0; i < this.widget.option.series.length; i++) {
          const datas = this.widget.option.series[i].data;
          for (let j = 0; j < datas.length; j++) {
            datas[j].areaStyle.opacity = val.customOpacity;
          }
        }
      },
      deep: true,
    },
    data: {
      handler() {
        this.refreshWidgetInfo();
      },
      deep: true,
    },
    refresh: {
      handler() {
        this.refreshWidgetInfo();
      },
    },
  },
  mounted() {
    this.refreshWidgetInfo();
  },
  destroyed() {
    this.recoveryRenderObject();
  },
  methods: {
    refreshWidgetInfo() {
      this.recoveryRenderObject();
      this.render = renderWidgetData(this.widget, this.refreshWidgetData);
    },
    refreshWidgetData(data) {
      const option = this.widget.option;
      option.radar.indicator = data.indicator;
      option.series.splice(1, option.series.length - 1);
      for (let i = 0; i < data.series.length; i++) {
        let chartData = data.series[i];
        let item = option.series[i];
        if (!item) {
          option.series.push(_.cloneDeep(option.series[0]));
          item = option.series[i];
        }
        item.data = chartData.data;
        // 添加雷达区域面积属性
        item.data.forEach((val) => {
          val.areaStyle = {
            opacity: option.radar.customOpacity, // 为0时不绘制区域面积，可用该属性控制是否绘制区域面积
          };
        });
      }
    },
    recoveryRenderObject() {
      if (this.render && this.render.apiTimer) {
        clearInterval(this.render.apiTimer);
        this.render.apiTimer = null;
      }
      if(this.render && this.render.websocket) {
        this.render.websocket.doDisconnect();
      }
    },
  },
};
</script>